using System;
using System.Collections.Generic;
using Volo.Abp.Domain.Entities.Auditing;

namespace CKY.AgentPlatform.Conversations;

/// <summary>
/// 对话状态枚举
/// </summary>
public enum ConversationStatus
{
    /// <summary>
    /// 进行中
    /// </summary>
    Active = 0,
    
    /// <summary>
    /// 已完成
    /// </summary>
    Completed = 1,
    
    /// <summary>
    /// 已取消
    /// </summary>
    Cancelled = 2,
    
    /// <summary>
    /// 错误
    /// </summary>
    Error = 3
}

/// <summary>
/// 消息角色枚举
/// </summary>
public enum MessageRole
{
    /// <summary>
    /// 用户
    /// </summary>
    User = 0,

    /// <summary>
    /// 助手
    /// </summary>
    Assistant = 1,

    /// <summary>
    /// 系统
    /// </summary>
    System = 2
}

/// <summary>
/// 对话消息角色枚举（向后兼容）
/// </summary>
public enum ConversationMessageRole
{
    /// <summary>
    /// 用户
    /// </summary>
    User = 0,

    /// <summary>
    /// 助手
    /// </summary>
    Assistant = 1,

    /// <summary>
    /// 系统
    /// </summary>
    System = 2
}

/// <summary>
/// 对话消息实体
/// </summary>
public class ConversationMessage : AuditedEntity<Guid>
{
    /// <summary>
    /// 对话ID
    /// </summary>
    public Guid ConversationId { get; set; }

    /// <summary>
    /// 消息角色
    /// </summary>
    public MessageRole Role { get; set; }

    /// <summary>
    /// 消息内容
    /// </summary>
    public string Content { get; set; }

    /// <summary>
    /// 消息顺序
    /// </summary>
    public int Order { get; set; }

    /// <summary>
    /// Token使用量
    /// </summary>
    public int TokenCount { get; set; }

    /// <summary>
    /// 响应时间（毫秒）
    /// </summary>
    public int ResponseTimeMs { get; set; }

    /// <summary>
    /// 错误信息
    /// </summary>
    public string ErrorMessage { get; set; }

    /// <summary>
    /// 元数据（JSON格式）
    /// </summary>
    public string Metadata { get; set; }

    /// <summary>
    /// 关联的对话
    /// </summary>
    public virtual Conversation Conversation { get; set; }

    protected ConversationMessage()
    {
        // EF Core requires parameterless constructor
    }

    /// <summary>
    /// 创建新的对话消息实例
    /// </summary>
    /// <param name="id">消息ID</param>
    /// <param name="conversationId">对话ID</param>
    /// <param name="role">消息角色</param>
    /// <param name="content">消息内容</param>
    /// <param name="order">消息顺序</param>
    public ConversationMessage(
        Guid id,
        Guid conversationId,
        MessageRole role,
        string content,
        int order) : base(id)
    {
        ConversationId = conversationId;
        Role = role;
        Content = content;
        Order = order;
        TokenCount = 0;
        ResponseTimeMs = 0;
        ErrorMessage = "";
        Metadata = "{}";
    }
}

/// <summary>
/// 对话实体 - 智能体对话记录管理
/// </summary>
public class Conversation : AuditedAggregateRoot<Guid>
{
    /// <summary>
    /// 对话标题
    /// </summary>
    public string Title { get; set; }

    /// <summary>
    /// 智能体ID
    /// </summary>
    public Guid AgentId { get; set; }

    /// <summary>
    /// 用户ID
    /// </summary>
    public Guid? UserId { get; set; }

    /// <summary>
    /// 对话状态
    /// </summary>
    public ConversationStatus Status { get; set; }

    /// <summary>
    /// 系统提示词
    /// </summary>
    public string SystemPrompt { get; set; }

    /// <summary>
    /// 消息数量
    /// </summary>
    public int MessageCount { get; set; }

    /// <summary>
    /// 总Token使用量
    /// </summary>
    public int TotalTokens { get; set; }

    /// <summary>
    /// 总响应时间（毫秒）
    /// </summary>
    public int TotalResponseTimeMs { get; set; }

    /// <summary>
    /// 开始时间
    /// </summary>
    public DateTime StartTime { get; set; }

    /// <summary>
    /// 结束时间
    /// </summary>
    public DateTime? EndTime { get; set; }

    /// <summary>
    /// 评分（1-5星）
    /// </summary>
    public int? Rating { get; set; }

    /// <summary>
    /// 反馈
    /// </summary>
    public string Feedback { get; set; }

    /// <summary>
    /// 标签
    /// </summary>
    public string Tags { get; set; }

    /// <summary>
    /// 会话ID（用于外部系统集成）
    /// </summary>
    public string SessionId { get; set; }

    /// <summary>
    /// 对话摘要
    /// </summary>
    public string Summary { get; set; }

    /// <summary>
    /// 元数据（JSON格式）
    /// </summary>
    public string Metadata { get; set; }

    /// <summary>
    /// 关联的智能体
    /// </summary>
    public virtual Agents.Agent Agent { get; set; }

    /// <summary>
    /// 对话消息列表
    /// </summary>
    public virtual ICollection<ConversationMessage> Messages { get; set; }

    protected Conversation()
    {
        // EF Core requires parameterless constructor
        Messages = new HashSet<ConversationMessage>();
    }

    /// <summary>
    /// 创建新的对话实例
    /// </summary>
    /// <param name="id">对话ID</param>
    /// <param name="title">对话标题</param>
    /// <param name="agentId">智能体ID</param>
    /// <param name="userId">用户ID</param>
    /// <param name="systemPrompt">系统提示词</param>
    public Conversation(
        Guid id,
        string title,
        Guid agentId,
        Guid? userId,
        string systemPrompt) : base(id)
    {
        Title = title;
        AgentId = agentId;
        UserId = userId;
        SystemPrompt = systemPrompt;
        Status = ConversationStatus.Active;
        MessageCount = 0;
        TotalTokens = 0;
        TotalResponseTimeMs = 0;
        StartTime = DateTime.UtcNow;
        Rating = null;
        Feedback = "";
        Tags = "";
        SessionId = Guid.NewGuid().ToString("N");
        Summary = "";
        Metadata = "{}";
        Messages = new HashSet<ConversationMessage>();
    }

    /// <summary>
    /// 添加消息到对话
    /// </summary>
    /// <param name="role">消息角色</param>
    /// <param name="content">消息内容</param>
    /// <param name="tokenCount">Token使用量</param>
    /// <param name="responseTimeMs">响应时间</param>
    /// <param name="errorMessage">错误信息</param>
    /// <returns>创建的消息</returns>
    public ConversationMessage AddMessage(
        MessageRole role,
        string content,
        int tokenCount = 0,
        int responseTimeMs = 0,
        string errorMessage = null)
    {
        var message = new ConversationMessage(
            Guid.NewGuid(),
            Id,
            role,
            content,
            MessageCount + 1);

        message.TokenCount = tokenCount;
        message.ResponseTimeMs = responseTimeMs;
        message.ErrorMessage = errorMessage ?? "";

        Messages.Add(message);
        MessageCount++;
        TotalTokens += tokenCount;
        TotalResponseTimeMs += responseTimeMs;

        return message;
    }

    /// <summary>
    /// 完成对话
    /// </summary>
    /// <param name="summary">对话摘要</param>
    public void Complete(string summary = null)
    {
        Status = ConversationStatus.Completed;
        EndTime = DateTime.UtcNow;
        Summary = summary ?? Summary;
    }

    /// <summary>
    /// 取消对话
    /// </summary>
    public void Cancel()
    {
        Status = ConversationStatus.Cancelled;
        EndTime = DateTime.UtcNow;
    }

    /// <summary>
    /// 设置错误状态
    /// </summary>
    /// <param name="errorMessage">错误信息</param>
    public void SetError(string errorMessage)
    {
        Status = ConversationStatus.Error;
        EndTime = DateTime.UtcNow;
        
        // 将错误信息添加到最后一条消息
        if (Messages.Count > 0)
        {
            var lastMessage = Messages.OrderByDescending(m => m.Order).First();
            lastMessage.ErrorMessage = errorMessage;
        }
    }

    /// <summary>
    /// 设置评分和反馈
    /// </summary>
    /// <param name="rating">评分（1-5）</param>
    /// <param name="feedback">反馈内容</param>
    public void SetRating(int rating, string feedback = null)
    {
        if (rating < 1 || rating > 5)
            throw new ArgumentException("评分必须在1-5之间", nameof(rating));

        Rating = rating;
        Feedback = feedback ?? "";
    }

    /// <summary>
    /// 获取对话持续时间
    /// </summary>
    /// <returns>持续时间</returns>
    public TimeSpan GetDuration()
    {
        var endTime = EndTime ?? DateTime.UtcNow;
        return endTime - StartTime;
    }

    /// <summary>
    /// 获取平均响应时间
    /// </summary>
    /// <returns>平均响应时间（毫秒）</returns>
    public double GetAverageResponseTime()
    {
        if (MessageCount == 0)
            return 0;

        return (double)TotalResponseTimeMs / MessageCount;
    }

    /// <summary>
    /// 获取平均Token使用量
    /// </summary>
    /// <returns>平均Token使用量</returns>
    public double GetAverageTokens()
    {
        if (MessageCount == 0)
            return 0;

        return (double)TotalTokens / MessageCount;
    }

    /// <summary>
    /// 获取对话摘要
    /// </summary>
    /// <returns>对话摘要</returns>
    public string GetConversationSummary()
    {
        if (!string.IsNullOrWhiteSpace(Summary))
            return Summary;

        // 如果没有预设摘要，生成简单摘要
        var userMessages = Messages.Where(m => m.Role == MessageRole.User).ToList();
        var assistantMessages = Messages.Where(m => m.Role == MessageRole.Assistant).ToList();

        return $"用户消息: {userMessages.Count}, 助手回复: {assistantMessages.Count}, 总Token: {TotalTokens}";
    }

    /// <summary>
    /// 检查对话是否可以进行
    /// </summary>
    /// <returns>是否可以继续对话</returns>
    public bool CanContinue()
    {
        return Status == ConversationStatus.Active;
    }

    /// <summary>
    /// 更新标签
    /// </summary>
    /// <param name="tags">标签字符串，逗号分隔</param>
    public void UpdateTags(string tags)
    {
        Tags = tags ?? "";
    }
}